package com.str.stack;
public class ArrayStack implements Stack {
    
  private static final int DEFAULT_SIZE = 10;
  private Object[] array;  // stack content
  private int top;         // top-1 is the index of the last element
                           // top also gives the depth of the stack.

// Constructor
  public ArrayStack() {
    array = new Object[DEFAULT_SIZE];
    top = 0;
  }

// Modifiers
  public void clear() {
    for (int i = 0; i < top; i++) array[i] = null;
    top = 0;
  }
    
  public void push(Object val) {
    if (top == array.length) expand();
    array[top++] = val;
  }

  public Object pop() {
    if (top == 0) 
      throw new IllegalStateException();
    Object val = array[--top];
    array[top] = null;
    return val;
  }

// Accessors
  public boolean isEmpty() { return top == 0; }

  public int size() { return top; }

  public Object peek() {                      
    if (top == 0) 
      throw new IllegalStateException();
    return array[top - 1];
  }

// Auxiliary methods
  private void expand() {
  	Object[] newArray = new Object[2 * array.length];
  	for (int i = 0; i < array.length; i++)
  	  newArray[i] = array[i];
  	array = newArray;
  }

  public String toString() {
    String buf = "[ ";
    for (int i = 0; i < top; i++) {
      if (i > 0) buf += ", ";
      buf += array[i];
    }
    buf += " ]";
    return buf;
  }
}